package com.yxkj.syh.app.huarong.activities.links.save;

import android.app.Application;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.lifecycle.MutableLiveData;

import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.syh.app.basic.App;
import com.syh.app.basic.base.view_model.BaseViewModel;
import com.syh.app.basic.bindingAdp.view_click.ClickEvent;
import com.syh.app.basic.utils.ComUtil;
import com.syh.app.basic.utils.Tooast;
import com.syh.app.basic.utils.net.ApiObserver;
import com.syh.app.basic.utils.regex.RegexUtils;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.yxkj.syh.app.huarong.bean.AliCityResponse;
import com.yxkj.syh.app.huarong.bean.AreaPlus;
import com.yxkj.syh.app.huarong.bean.Linkman;
import com.yxkj.syh.app.huarong.bean.LinkmanResponse;
import com.yxkj.syh.app.huarong.bean.SaveLinkmanResponse;
import com.yxkj.syh.app.huarong.constants.ArouterPath;
import com.yxkj.syh.app.huarong.data_center.model.AliCityModel;
import com.yxkj.syh.app.huarong.data_center.model.CommonModel;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import chihane.jdaddressselector.AddressProvider;
import chihane.jdaddressselector.model.City;
import chihane.jdaddressselector.model.County;
import chihane.jdaddressselector.model.Province;
import chihane.jdaddressselector.model.Street;

/**
 * 创建者：SYH
 * 时间：2020/6/4 11:28
 * 编辑者：SYH、
 * 标签：
 * 补充说明：
 */
public class EditLinkVM extends BaseViewModel<ActivityEvent> {

    private Linkman linkman;
    boolean isOrderRequested = false;

    public EditLinkVM(@NonNull Application application) {
        super(application);
    }

    public ObservableField<String> ofForm1 = new ObservableField<String>() {
        @Override
        public void set(String value) {
            super.set(value);
            setCommitEnable(value, ofForm2.get(), ofForm3.get(), ofForm4.get(), ofForm5.get());
        }
    };
    public ObservableField<String> ofForm2 = new ObservableField<String>() {
        @Override
        public void set(String value) {
            super.set(value);
            setCommitEnable(value, ofForm1.get(), ofForm3.get(), ofForm4.get(), ofForm5.get());
        }
    };
    public ObservableField<String> ofForm3 = new ObservableField<String>() {
        @Override
        public void set(String value) {
            super.set(value);
            setCommitEnable(value, ofForm2.get(), ofForm1.get(), ofForm4.get(), ofForm5.get());
        }
    };
    public ObservableField<String> ofForm4Source = new ObservableField<>();
    public ObservableField<String> ofForm4 = new ObservableField<String>() {
        @Override
        public void set(String value) {
            super.set(value);
            setCommitEnable(value, ofForm2.get(), ofForm3.get(), ofForm1.get(), ofForm5.get());
        }
    };
    public ObservableField<String> ofForm4_ids = new ObservableField<>();
    public ObservableField<String> ofForm5 = new ObservableField<String>() {
        @Override
        public void set(String value) {
            super.set(value);
            setCommitEnable(value, ofForm2.get(), ofForm3.get(), ofForm4.get(), ofForm1.get());
        }
    };
    public ObservableField<Boolean> ofEditNameEnable = new ObservableField<>(Boolean.TRUE);
    public ObservableField<Boolean> ofMainInfoEditEnable = new ObservableField<>(Boolean.TRUE);

    public MutableLiveData<Linkman> mldSaveSuccess = new MutableLiveData<>();


    public ClickEvent saveClick = new ClickEvent() {
        @Override
        public void onClick(View view) {
            if (!RegexUtils.isZh(ofForm2.get())) {
                Tooast.normalInfo("姓名不合法");
                return;
            }
            if (!RegexUtils.isMobileSimple(ofForm3.get())) {
                Tooast.normalInfo("请输入正确格式手机号");
                return;
            }
            Linkman linkman = new Linkman();
            if (EditLinkVM.this.linkman != null) {
                linkman.setId(EditLinkVM.this.linkman.getId());
            }
            linkman.setName(ofForm1.get());
            linkman.setLinkman(ofForm2.get());
            linkman.setMobile(ofForm3.get());
            linkman.setArea(ofForm4Source.get());
            linkman.setAddress(ofForm5.get());
            linkman.setAreaIds(ofForm4_ids.get());
            saveLinkman(linkman);
        }
    };

    public ObservableField<Boolean> ofCommitEnable = new ObservableField(Boolean.FALSE);
    public ObservableField<Boolean> ofPaymentEnable = new ObservableField(Boolean.FALSE);

    private void setLinkman(Linkman linkman) {
        this.linkman = linkman;
        ofForm1.set(linkman.getName());
        ofForm2.set(linkman.getLinkman());
        ofForm3.set(linkman.getMobile());
        ofForm4Source.set(linkman.getArea());
        ofForm4.set(linkman.getArea().replace("/",""));
        ofForm5.set(linkman.getAddress());
//        ofPaymentEnable.set(false);
    }

    public void setOrderRequested(boolean orderRequested) {
        isOrderRequested = orderRequested;
    }

    public Linkman getLinkman() {
        return linkman;
    }

    private void setCommitEnable(String... strings) {
        if (ComUtil.hasEmpty(strings)) {
            if (ofCommitEnable.get()) {
                ofCommitEnable.set(false);
            }
        } else {
            if (!ofCommitEnable.get()) {
                ofCommitEnable.set(true);
            }
        }
    }

    public void linkmanInfo(long id) {
        CommonModel.getCommonModel().linkInfo(id, mLifecycleProvider.bindToLifecycle(), new ApiObserver<LinkmanResponse>() {
            @Override
            public void onSuccess(LinkmanResponse linkmanResponse) {
                setLinkman(linkmanResponse.getData());
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
            }
        });
    }

    public void saveLinkman(Linkman linkman) {

        showLoading("saveLinkman");
        CommonModel.getCommonModel().saveLinkman(linkman, mLifecycleProvider.bindToLifecycle(), new ApiObserver<SaveLinkmanResponse>() {
            @Override
            public void onSuccess(SaveLinkmanResponse response) {
                hideLoading("saveLinkman");
                mldSaveSuccess.setValue(response.getData());
            }

            @Override
            public void onFailed(int code, String msg) {
                hideLoading("saveLinkman");
                Tooast.warning(msg);
            }
        });
    }

    /**
     * 地址选择器的数据源提供者
     */
    public AddressProvider addressProvider = new AddressProvider() {
        @Override
        public void provideProvinces(AddressReceiver<Province> addressReceiver) {
            addressReceiver.send(getProvince());
        }

        @Override
        public void provideCitiesWith(int provinceId, AddressReceiver<City> addressReceiver) {
            cities(provinceId, addressReceiver);
        }

        @Override
        public void provideCountiesWith(int cityId, AddressReceiver<County> addressReceiver) {
            counties(cityId, addressReceiver);
        }

        @Override
        public void provideStreetsWith(int countyId, AddressReceiver<Street> addressReceiver) {
            addressReceiver.send(null);
        }
    };

    /**
     * 查市
     */
    public void cities(int provinceId, AddressProvider.AddressReceiver<City> addressReceiver) {

        AliCityModel.getAliCityModel().getAliCity(getAreaPlusId(1, provinceId), mLifecycleProvider.bindToLifecycle(), new ApiObserver<AliCityResponse>() {
            @Override
            public void onSuccess(AliCityResponse response) {
                if (response.getShowapi_res_code() == 0) {
                    areaLevel2Pluses.clear();
                    areaLevel2Pluses.addAll(response.getShowapi_res_body().getData());
                    cities.clear();
                    for (int i = 0; i < areaLevel2Pluses.size(); i++) {
                        AreaPlus areaPlus = areaLevel2Pluses.get(i);
                        City city = new City();
                        city.id = i + 1;
                        city.name = areaPlus.getAreaName();
                        city.province_id = provinceId;
                        areaPlus.setCity(city);
                        cities.add(city);
                    }
                    addressReceiver.send(cities);
                }
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
            }
        });
    }

    /**
     * 查区县
     */
    public void counties(int cityId, AddressProvider.AddressReceiver<County> addressReceiver) {
        AliCityModel.getAliCityModel().getAliCity(getAreaPlusId(2, cityId), mLifecycleProvider.bindToLifecycle(), new ApiObserver<AliCityResponse>() {
            @Override
            public void onSuccess(AliCityResponse response) {
                if (response.getShowapi_res_code() == 0) {
                    areaLevel3Pluses.clear();
                    areaLevel3Pluses.addAll(response.getShowapi_res_body().getData());
                    counties.clear();
                    for (int i = 0; i < areaLevel3Pluses.size(); i++) {
                        AreaPlus areaPlus = areaLevel3Pluses.get(i);
                        County county = new County();
                        county.id = i + 1;
                        county.name = areaPlus.getAreaName();
                        county.city_id = cityId;
                        areaPlus.setCounty(county);
                        counties.add(county);
                    }
                    addressReceiver.send(counties);
                }
            }

            @Override
            public void onFailed(int code, String msg) {
                Tooast.warning(msg);
            }
        });
    }


    private List<AreaPlus> areaLevel1Pluses = new ArrayList<>();
    private List<AreaPlus> areaLevel2Pluses = new ArrayList<>();
    private List<AreaPlus> areaLevel3Pluses = new ArrayList<>();
    private List<Province> provinces = new ArrayList<>();
    private List<City> cities = new ArrayList<>();
    private List<County> counties = new ArrayList<>();

    /**
     * 读省
     *
     * @return
     */
    private List<Province> getProvince() {
        if (provinces.size() == 0) {
            try {
                // 获取json文件数据源,流的方式呈现
                InputStream inputStream = App.getApplication().getAssets().open("province.json");
                // 读取JSON文件流
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String temp = "";
                String jsonSource = "";
                //一行一行的读取
                while ((temp = bufferedReader.readLine()) != null) {
                    jsonSource += temp;
                }
                //关闭
                bufferedReader.close();
                inputStream.close();

                JSONObject jsonObject = new JSONObject(jsonSource);
                List<AreaPlus> areaPluses = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<List<AreaPlus>>() {
                }.getType());

                areaLevel1Pluses.clear();
                areaLevel1Pluses.addAll(areaPluses);

                for (int i = 0; i < areaLevel1Pluses.size(); i++) {
                    AreaPlus provincePlus = areaLevel1Pluses.get(i);
                    Province province = new Province();
                    province.name = provincePlus.getAreaName();
                    province.id = i + 1;
                    provinces.add(province);
                    provincePlus.setProvince(province);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return provinces;
    }

    /**
     * 查 AreaPlusId
     *
     * @param subId      子类 id
     */
    public long getAreaPlusId(int level, int subId) {
        long id = 0l;

        if (level == 1) {
            for (AreaPlus areaPlus : areaLevel1Pluses) {
                if (areaPlus.getProvince().id == subId) {
                    id = Long.decode(areaPlus.getId());
                    break;
                }
            }
        } else if (level == 2) {
            for (AreaPlus areaPlus : areaLevel2Pluses) {
                if (areaPlus.getCity().id == subId) {
                    id = Long.decode(areaPlus.getId());
                    break;
                }
            }
        } else if (level == 3) {
            for (AreaPlus areaPlus : areaLevel3Pluses) {
                if (areaPlus.getCounty().id == subId) {
                    id = Long.decode(areaPlus.getId());
                    break;
                }
            }
        }
        return id;
    }
}
